
import { headers } from "next/headers";
export type ActionResponse<T> = {
  code: number;
  message: string;
  data?: T;
};
/** 
 * 泛型 表示返回值的类型
 * 
 * T返回值的类型，R表示参数类型
 */
export function handlerAction<T, R = any>(handler: Function) {
  return async (args?: R): Promise<ActionResponse<T>> => {
    try {
      const headersList = await headers();
      const referer = headersList.get("referer");
      // console.log(referer);
      // console.log(1111111111);
      const result = await handler(args);
      return {
        data: result as T,
        message: "success",
        code: 0,
      };
    } catch (err: any) {
      if (err.name == "PrismaClientKnownRequestError") {
        return {
          message: err.message,
          code: 400,
        };
      }
      if(err.name==='Error'){
        console.log(err.message);
        return {
          message: err.message,
          code: 400,
        };
      }
      // return errorHandler(err)
      return {
        message: err.toString(),
        code: 500,
      };
    }
  };
}
